package com.dongqi.myblog.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dongqi.myblog.po.TUser;
import com.dongqi.myblog.service.TUserService;
import com.dongqi.myblog.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dongqi
 * @since 2020-08-03
 */
@Controller
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private TUserService userService;

    /**
     * 跳转到登录页面
     */
    @GetMapping
    public String toLogin(Model model){
        Random random = new Random();
        int i = random.nextInt(5)+1;
        model.addAttribute("bg",i+".png");
        return "admin/login";
    }

    /**
     * 登录功能
     */
    @PostMapping("/login")
    public String login(String username,
                        String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        wrapper.eq("password", MD5Utils.code(password));
        TUser user = userService.getOne(wrapper);
        if (user!=null){
            user.setPassword(null);
            session.setAttribute("user",user);
            return "admin/index";
        } else {
            attributes.addFlashAttribute("message","用户名或密码错误");
            return "redirect:/admin";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }

    /**
     * 跳转到修改admin个人信息页面
     * @return
     */
    @GetMapping("/user")
    public String toUpdate(Model model){
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("type",1);
        TUser user = userService.getOne(wrapper);
        model.addAttribute("user",user);
        return "admin/user-update";
    }

    @PostMapping("/user/{id}")
    public String update(@PathVariable Long id,
                         MultipartFile file,
                         TUser user){
        userService.saveUser(id,user,file);
        return "redirect:/admin/logout";

    }

}

